<?php
// +----------------------------------------------------------------------
//            -------------------------
//           /   / ----------------\  \
//          /   /             \  \
//         /   /              /  /
//        /   /    /-------------- /  /
//       /   /    /-------------------\  \
//      /   /                   \  \
//     /   /                     \  \
//    /   /                      /  /
//   /   /      /----------------------- /  /
//  /-----/      /---------------------------/
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://baimifan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Sage 2016/5/6  15:34
// +----------------------------------------------------------------------
namespace Admin\Controller;
class RentController extends CashierBaseController {

    function index() {
        $this->display();
    }

    //借阅图书
    function doRent() {
        $data = I("post.");
        $blist = explode("," , I("post.liststr"));
        $blist = array_count_values($blist);
        $summary = '线下借阅,借阅清单：';
        foreach ($blist as $k => $v) {
            $summary .= "ID:{$k},{$v}本;";
        }
        $summary .= "运费:0元,购书费:0元,共:0元,总价:0元";
        //生成支付订单pay
        $Pay = M("Pay");
        $Pay->startTrans();
        $map_pay = ["user_id" => I("post.user_id") , "status" => 1 , "type" => 1 , "way" => "cash" , "summary" => $summary , "money" => 0 , "money_real" => 0 , "money_zero" => 0];
        $pay_id = $Pay->data($map_pay)->add();
        if (!$pay_id) {
            $Pay->rollback();
            $this->error("借阅失败");
        }
        //生成订单order
        $Order = M("Order_book");
        $map_order = ["user_id" => I("post.user_id") , "money" => 0 , "price_freight" => 0 , "type" => 1 , "address" => "{'info':'线下借阅'}" , "state_order" => "3" , "pay_id" => $pay_id , "is_freightfree" => 1,'is_online'=>'1'];

        $order_id = $Order->data($map_order)->add();
        // 统计后台用户借书数据使用
//        M("admin_order")->data(['admin_id' => session('admin_user.user_id'), 'order_id' => $order_id])->add();
        if (!$order_id) {
            $Order->rollback();
            $this->error("借阅失败");
        }
        //生成订单图书数据
        $Orderbook = M("Order_has_book");   //订单包含的书
        foreach ($blist as $k => $v) {
            // 统计后台用户借书数据使用
            M("admin_order")->data(['admin_id' => session('admin_user.user_id'), 'order_id' => $order_id,'book_id' => $k ])->add();

            $map_book[] = ["order_id" => $order_id , "book_id" => $k , "quantity" => $v , "type" => 1];
            $rr=M('Book')->where(['book_id'=>$k])->setDec('stock_rent',$v);//减速库存
            if(!$rr){
                $Orderbook->rollback();
                $this->error("库存不足");
            }
        }


        $r = $Orderbook->addAll($map_book);
        if ($r) {
            $Orderbook->commit();
            $this->success("借阅成功");
        } else {
            $Orderbook->rollback();
            $this->error("借阅失败");
        }
    }

    function orderShow() {
        $order_id = I("get.order_id");
        $d = [];
        $da = M("Order_book")->where(["order_id" => $order_id])->find();
        $d['order_id'] = $da['order_id']; //订单号
        $d['money_b'] = $da['money']; //原价
        $d['type'] = $da['type'] == 0 ? "购书" : "借阅";
        $d['discount_buy'] = $da['discount_buy']; //折扣
        $db = M("Pay")->where(["pay_id" => $da['pay_id']])->find();
        $d['money'] = $db['money']; //实际价格
        $d['money_real'] = $db['money_real']; //实收
        $d['money_zero'] = $db['money_zero']; //找零
        $d['create_time'] = $db['create_time']; //找零
        $dc = M("View_order_has_book")->where(["order_id" => $order_id])->field("sm,dj,quantity")->select();
        $d['book_list'] = $dc;
        $this->assign("d" , $d);
        $this->display();
    }

    //借阅前检查
    function rentCheck() {
        $card_id = I("post.card_id");
        $d = M("Card")->where(['card_id' => $card_id])->find();
        if (!$d) {
            $r = ["status" => "error" , "data" => "此卡不存在"];
            echo json_encode($r);

            return;
        }
        if ($d['is_lock'] == -1) {
            $r = ["status" => "error" , "data" => "此卡已挂失冻结，不可借阅"];
            echo json_encode($r);
            return;
        }
        
        $delay_time=json_decode($d['delay_time']);
        if(!empty($delay_time) && strtotime($delay_time->start_time) <time() && strtotime($delay_time->end_time) >time()){
            $r = ["status" => "error" , "data" => "此卡在延期冻结时间段内，不可借阅"];
            echo json_encode($r);
            return;
        }

        //已过期无法借阅
        if(strtotime($d['create_time'])>time() || strtotime($d['expire_time'])<time()){
            $r = ["status" => "error" , "data" => "此卡已过期，无法借阅"];
            echo json_encode($r);
            return;
        }

        $blist = explode("," , I("post.liststr"));
        $blist = array_count_values($blist);
        $sum = 0;
        foreach ($blist as $k => $v) {
            $sum += $v;
            $c = M("Book")->where(["book_id" => $k , "stock_rent" => ['egt' , $v]])->count();
//            $c = M("Book")->where(["book_id" => $k ])->count(); //支持负库存
            if ($c == 0) {
                $r = ["status" => "error" , "data" => "库存不足"];
                echo json_encode($r);

                return;
            }
        }


        //判断是否超出借书限制
        //计算还有多少书未还
        $do = M("Order_book")->where(["user_id" => $d["user_id"] , "type" => 1 , "state_order" => 3])->field("order_id")->select();//取【该用户】状态为【已收货】的【借书】订单
        if (!$do) {//如果没有订单
            $c=0;
        }else{
            $m_order_id = [];//【订单号】数组初始化
            foreach ($do as $k => $v) {
                array_push($m_order_id , $v['order_id']);//把每条订单的订单号加入数组中
            }
            $map['order_id'] = ["in" , $m_order_id];    //订单号in
            $map['type'] = 1;                           //类型为借书
            $map['is_backed'] = 0;                      //状态为未归还
            $c = M("View_order_has_book")->where($map)->count();    //查未归还书的条数
        }
        //判断未还的书加上本次要借的书，是否超出限制
        if($sum+$c > C("rentmax_md")){
            $r = ["status" => "error" , "data" => "超出借书限制"];
            echo json_encode($r);
            return;
        }



        $r = ["status" => "success" , "data" => "可购买"];
        echo json_encode($r);

        return;
    }

    //获取用户借阅记录
    function getRecord() {
        $user_id = I("post.user_id");
        $num = 5; //分页数目
        $page = I("post.page") == "" ? 1 : I("post.page"); //当前页码
        $do = M("Order_book")->where(["user_id" => $user_id , "type" => 1 , "state_order" => 3])->field("order_id")->select();//取【该用户】状态为【已收货】的【借书】订单
        if (!$do) {//如果没有订单
            $r = ["status" => "success" , "data" => [] , "total" => 0 , "page" => 1];
            echo json_encode($r);

            return;
        }
        $m_order_id = [];//【订单号】数组初始化
        foreach ($do as $k => $v) {
            array_push($m_order_id , $v['order_id']);//把每条订单的订单号加入数组中
        }
        $map['order_id'] = ["in" , $m_order_id];    //订单号in
        $map['type'] = 1;                           //类型为借书
        $map['is_backed'] = 0;                      //状态为未归还
        $c = M("View_order_has_book")->where($map)->count();    //查未归还书的条数
//        $c = ceil($c / $num);
        //查未归还书的详情
        $d = M("View_order_has_book")->where($map)->field("order_id,book_id,quantity,num_backed,num_broken,sm,tm,is_backed,create_time")->order('create_time desc')->select();
        $r = ["status" => "success" , "data" => $d , "total" => $c , "page" => $page];


        echo json_encode($r);
    }
}